#!/bin/bash
# $ ./add-app-makefile-c5socboot [MAKEFILE]
# Add targets for C5 SoC hosted boot

MAKE_FILE=$1

cat >> ${MAKE_FILE} <<'Heredoc'

# Rules for converting elf to bin
ELF_TO_BIN_SUFFIX := -bin
DRV_NAME := $(basename $(ELF))
BIN_NAME := $(addsuffix .bin, $(DRV_NAME))
BIN := $(BIN_NAME)
ELF_TO_BIN_TARGET := $(addsuffix $(ELF_TO_BIN_SUFFIX), $(DRV_NAME))
REMOVE_SECTION_ARG := -R .tc_mem -R .exceptions

.PHONY : fpgaboot_bin
fpgaboot_bin : $(ELF_TO_BIN_TARGET)

.PHONY : $(ELF_TO_BIN_TARGET)
$(ELF_TO_BIN_TARGET) : $(ELF)
	@$(ECHO) Info: Converting $(ELF) to $(BIN_NAME)
	$(OBJCOPY) $(REMOVE_SECTION_ARG) -O binary $(ELF) $(BIN)

clean::
	$(RM) -r $(BIN)

# Rules for preparing rbf
SOF_FILE := $(wildcard $(QUARTUS_PROJECT_DIR)/*.sof)
INPUT_RBF_NAME := $(basename  $(notdir $(SOF_FILE)))

INPUT_RBF_FILE := $(QUARTUS_PROJECT_DIR)/$(INPUT_RBF_NAME).rbf
OUTPUT_RBF_NAME := fpga


.PHONY : fpgaboot_rbf
fpgaboot_rbf: $(OUTPUT_RBF_NAME)-rbf

$(OUTPUT_RBF_NAME)-rbf : $(INPUT_RBF_FILE)
	cp $(INPUT_RBF_FILE) $(OUTPUT_RBF_NAME).rbf

$(INPUT_RBF_FILE) : mem_init_generate $(SOF_FILE)
	@$(ECHO) Info: Update memory initialization in $(SOF_FILE)
	$(CP) -f $(HEX_FILES) $(QUARTUS_PROJECT_DIR)
	$(MAKE) -C $(QUARTUS_PROJECT_DIR) update-mif
	@$(ECHO) Info: Converting $(SOF_FILE) to $(INPUT_RBF_FILE)
	quartus_cpf -c $(SOF_FILE) $(INPUT_RBF_FILE)

clean::
	$(RM) -r $(OUTPUT_RBF_NAME).rbf

fpgaboot: fpgaboot_rbf fpgaboot_bin

# Rule for C5 SoC hosted boot help output
help::
	@$(ECHO)
	@$(ECHO) "  C5 SoC hosted boot targets:"
	@$(ECHO) "    fpgaboot          - Generate all FPGA bootfiles (.rbf and .bin)"
	@$(ECHO) "    fpgaboot_rbf      - Generate FPGA bitstream rbf"
	@$(ECHO) "    fpgaboot_bin      - Convert Nios II elf to binary"

Heredoc
